package com.yenlien.traceyun.plant.service;

import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.common.bean.UserInfo;
import com.yenlien.traceyun.common.utils.Tools;
import com.yenlien.traceyun.plant.dao.ColdDevDao;
import com.yenlien.traceyun.plant.entity.ColdDev;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Date 2022/8/30
 * @Author jiaLong
 * @Descript
 */
@Service
public class ColdDevService {

    @Autowired
    private ColdDevDao coldDevDao;



    public ColdDev save(ColdDev coldDev) {
        if(StringUtils.isEmpty(coldDev.getId())){
            coldDev.setCreateTime(Tools.getCurrentTime());
            coldDev.setState("1");
            return coldDevDao.save(coldDev);
        }else {
            return coldDevDao.save(coldDev);
        }
    }

//    public ColdStorage update(ColdStorage coldStorage) {
//        return ColdStorageDao.save(ColdStorage);
//    }


    public Page<ColdDev> findByList(ColdDev coldDev) {
        UserInfo userInfo = UserAuthUtil.getLoginUser();
        Pageable pageable = PageRequest.of(coldDev.getPage(), coldDev.getPageSize());
        return coldDevDao.findAll((Root<ColdDev> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (!StringUtils.isEmpty(coldDev.getDevName())) {
                list.add(cb.like(root.get("devName"), "%" + coldDev.getDevName() + "%"));
            }
            if (!StringUtils.isEmpty(coldDev.getColdName())) {
                list.add(cb.like(root.get("coldName"), "%" + coldDev.getColdName() + "%"));
            }
            if(!"1".equals(userInfo.getIsManage())){
                list.add(cb.like(root.get("companyId"), userInfo.getCompanyId()));
            }
            return cb.and(list.toArray(new Predicate[list.size()]));
        }, pageable);
    }

    public List<ColdDev> findAll(){
        return coldDevDao.findAll();
    }


    public List<ColdDev> findByCompanyIdAndState(String state){
        UserInfo userInfo = UserAuthUtil.getLoginUser();
        if(!"1".equals(userInfo.getIsManage())){
            return coldDevDao.findByCompanyIdAndState(userInfo.getCompanyId(), state);
        }
        return coldDevDao.findByState(state);
    }






}
